package com.heatup.apt.management.service.datacenter.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.heatup.apt.common.dao.CoachSigninLogMapper;
import com.heatup.apt.common.dao.CourseInfoMapper;
import com.heatup.apt.common.dao.CourseSignMapper;
import com.heatup.apt.common.dao.DataCenterMapper;
import com.heatup.apt.common.dao.StoreBalanceDetailMapper;
import com.heatup.apt.common.dao.store.StoreInfoMapper;
import com.heatup.apt.common.util.DateUtils;
import com.heatup.apt.common.util.StringUtil;
import com.heatup.apt.management.service.datacenter.DataAnalysisService;
import com.heatup.apt.model.coach.CampCountFeeDetail;
import com.heatup.apt.model.course.CoachFeeDetailVo;
import com.heatup.apt.model.course.CoursePrivteFeeVO;
import com.heatup.apt.model.datacenter.DataCenterOrderDetailModel;
import com.heatup.apt.model.datacenter.DataCenterOrderIncomeAmtModel;
import com.heatup.apt.model.datacenter.DataCenterSortResultModel;
import com.heatup.apt.model.datacenter.DataCenterUserStort;
import com.heatup.apt.model.datacenter.DataCenterVIPDeatilModel;
import com.heatup.apt.model.datacenter.StoreBalanceDetail;
import com.heatup.apt.model.store.StoreInfo;

@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {
	// 日志
	private Logger logger = LoggerFactory.getLogger(DataAnalysisServiceImpl.class);
	
	@Autowired
	private DataCenterMapper dataCenterMapper;
	
	@Autowired
	private StoreInfoMapper storeInfoMapper;
	@Autowired
	private CoachSigninLogMapper coachSigninLogMapper;
	@Autowired
	private CourseSignMapper courseSignMapper;
	@Autowired
	private CourseInfoMapper courseInfoMapper;
	@Autowired
	private StoreBalanceDetailMapper storeBalanceDetailMapper;
	
	/**
	 * 大盘数据分析 第一层数据异步加载
	 * 这里是一层一层的加载
	 * 不是全部一下子加载
	 */
	@Override
	public Map<String, Object> queryDataAnalysisLevelOne(Map<String, Object> parameMap) {
		// TODO Auto-generated method stub
		logger.info("=========================== ajax select queryDataAnalysisLevelOne start ================");
		Integer storeId = (Integer) parameMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = "";
		String type = (String) parameMap.get("type");
		DecimalFormat df=new DecimalFormat(",###,###.###");
		try {
			String dateTime = (String)parameMap.get("dateTime");
			if(StringUtil.isEmpty(dateTime)){
				startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
				parameMap.put("dateTime", startDate);
			}else{
				if("1".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else if("2".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else{
					yearMonth = dateTime ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		// 1当期零售订单笔数
		Integer orderCount = dataCenterMapper.queryRetailOrderCount(storeId, startDate, endDate, yearMonth);
		orderCount = orderCount>0?orderCount:0;
		// 2当期零售流水
		BigDecimal orderWater = BigDecimal.valueOf(0);
		orderWater = orderWater.add(dataCenterMapper.queryRetailOrderRunningAccountAmt(storeId, startDate, endDate, yearMonth));
		// 3当期零售实收金额
		List<DataCenterOrderIncomeAmtModel> listAmt = dataCenterMapper.queryRetailRealIncomeAmt(storeId, startDate, endDate, yearMonth);
		BigDecimal orderRevenueAmt = BigDecimal.valueOf(0);
		if(listAmt.size() != 0){
			for(DataCenterOrderIncomeAmtModel d:listAmt){
				orderRevenueAmt = orderRevenueAmt.add(d.getIncomeAmt());
			}
		}
		// 4当期付费总人数
		List<DataCenterOrderDetailModel> orderPayList = dataCenterMapper.queryPayerCountDetail(storeId, startDate, endDate, yearMonth);
		Integer orderPayNumber = 0;
		if(orderPayList.size() != 0){
			for(DataCenterOrderDetailModel d:orderPayList){
				orderPayNumber = orderPayNumber + d.getAllOrderCount();
			}
			
		}
		parameMap.put("orderCount", df.format(orderCount));
		parameMap.put("orderWater", df.format(orderWater.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("orderRevenueAmt", df.format(orderRevenueAmt.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("orderPayNumber", df.format(orderPayNumber));
		logger.info("=========================== ajax select queryDataAnalysisLevelOne end   ================");
		return parameMap;
	}
	
	/**
	 * 大盘数据分析 第二层数据异步加载
	 * 这里是一层一层的加载
	 * 不是全部一下子加载
	 */
	@Override
	public Map<String, Object> queryDataAnalysisLevelTow(Map<String, Object> parameMap) {
		// TODO Auto-generated method stub
		logger.info("=========================== ajax select queryDataAnalysisLevelTow start ================");
		Integer storeId = (Integer) parameMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = null;
		String type = (String) parameMap.get("type");
		DecimalFormat df=new DecimalFormat(",###,###.###");
		try {
			String dateTime = (String)parameMap.get("dateTime");
			if(StringUtil.isEmpty(dateTime)){
				startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
				parameMap.put("dateTime", startDate);
			}else{
				if("1".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else if("2".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else{
					yearMonth = dateTime ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 1当期新增会员
		Integer vipNum = dataCenterMapper.queryNweVipCount(storeId, startDate, endDate, yearMonth);
		vipNum = vipNum > 0 ?vipNum : 0;
		// 2当期新增会员流水
		BigDecimal vipWater = BigDecimal.valueOf(0);
		vipWater = vipWater.add(dataCenterMapper.queryVIPOrderAmt(storeId, startDate, endDate, yearMonth));
		// 3当期会员实收
		BigDecimal vipAmt = BigDecimal.valueOf(0);
		vipAmt = vipAmt.add(dataCenterMapper.queryVipRealIncomeAmt(storeId, StringUtil.isEmpty(yearMonth) == false ? yearMonth+"-01":startDate, StringUtil.isEmpty(yearMonth) == false ? DateUtils.andMonth(yearMonth+"-01", 1):endDate));
		// 4当期流失会员数
		Integer vipLost = dataCenterMapper.queryVipLost(storeId, startDate, endDate, StringUtil.isEmpty(yearMonth) == false ? yearMonth+"-01":yearMonth);
		vipLost = vipLost > 0 ? vipLost : 0;
		parameMap.put("vipNum", df.format(vipNum));
		parameMap.put("vipWater", df.format(vipWater.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("vipAmt", df.format(vipAmt.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("vipLost", df.format(vipLost));
		logger.info("=========================== ajax select queryDataAnalysisLevelTow end  ================");
		return parameMap;
	}
	
	/**
	 * 大盘数据分析 第三层数据异步加载
	 * 这里是一层一层的加载
	 * 不是全部一下子加载
	 */
	@Override
	public Map<String, Object> queryDataAnalysisLevelThree(Map<String, Object> parameMap) {
		logger.info("=========================== ajax select queryDataAnalysisLevelThree start ================");
		Integer storeId = (Integer) parameMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = "";
		String type = (String) parameMap.get("type");
		DecimalFormat df=new DecimalFormat(",###,###.##");
		try {
			String dateTime = (String)parameMap.get("dateTime");
			if(StringUtil.isEmpty(dateTime)){
				startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
				parameMap.put("dateTime", startDate);
			}else{
				if("1".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else if("2".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else{
					yearMonth = dateTime ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 1当期会员零售转化率
		BigDecimal vipConversionRate = BigDecimal.valueOf(0);
		vipConversionRate = vipConversionRate.add(dataCenterMapper.queryVipRetailRechargeRate(storeId, yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ? DateUtils.andMonth(yearMonth+"-01", 1):endDate));
		// 2当期会员自助转化率
		BigDecimal VipSelfConversionRate = BigDecimal.valueOf(0);
		VipSelfConversionRate = VipSelfConversionRate.add(dataCenterMapper.queryVipSelfRechargeRate(storeId, yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ? DateUtils.andMonth(yearMonth+"-01", 1):endDate));
		// 3当期零售复购率
		BigDecimal retailRechargeRate = VipSelfConversionRate = BigDecimal.valueOf(0);
		retailRechargeRate = retailRechargeRate.add(dataCenterMapper.queryRetailRepeatChargeRate(yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ?  DateUtils.andMonth(yearMonth+"-01", 1):endDate, "2"));
		// 4当期排课量
		Integer courseCount = dataCenterMapper.querySchedulerCourseCount(storeId, yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ? DateUtils.andMonth(yearMonth+"-01", 1):endDate);
		courseCount = courseCount > 0 ? courseCount : 0 ;
		parameMap.put("vipConversionRate", vipConversionRate);
		parameMap.put("VipSelfConversionRate", VipSelfConversionRate);
		parameMap.put("retailRechargeRate", retailRechargeRate);
		parameMap.put("courseCount", courseCount);
		logger.info("=========================== ajax select queryDataAnalysisLevelThree start ================");
		return parameMap;
	}
	
	/**
	 * 大盘数据分析 第四层数据异步加载
	 * 这里是一层一层的加载
	 * 不是全部一下子加载
	 */
	@Override
	public Map<String, Object> queryDataAnalysisLevelFour(Map<String, Object> parameMap) {
		logger.info("=========================== ajax select queryDataAnalysisLevelFour start ================");
		Integer storeId = (Integer) parameMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = "";
		String type = (String) parameMap.get("type");
		DecimalFormat df=new DecimalFormat(",###,###.##");
		try {
			String dateTime = (String)parameMap.get("dateTime");
			if(StringUtil.isEmpty(dateTime)){
				startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
				parameMap.put("dateTime", startDate);
			}else{
				if("1".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else if("2".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else{
					yearMonth = dateTime ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 1当期团课满课率
		BigDecimal teamFullClassRate = BigDecimal.valueOf(0); 
		teamFullClassRate = teamFullClassRate.add(dataCenterMapper.queryTeamFullClassRate(storeId, yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ?  DateUtils.andMonth(yearMonth+"-01", 1):endDate));
		// 2当期用户平均购买次数
		BigDecimal averagePayCount = BigDecimal.valueOf(0); 
		averagePayCount = averagePayCount.add(dataCenterMapper.queryAveragePayNumberToUser(storeId, startDate, endDate,yearMonth));// 暂留
		// 3 教练课时费
		parameMap.put("storeId", storeId);
		parameMap.put("yearMonth", yearMonth);
		parameMap.put("startDate", startDate);
		parameMap.put("endDate", endDate);
		StoreBalanceDetail storeBalanceDetail = storeBalanceDetailMapper.queryStoreBalanceDetailBy(parameMap);
		BigDecimal coachAmt = BigDecimal.valueOf(0);
		if(storeBalanceDetail != null && storeBalanceDetail.getCoachCourseFee() != null && storeBalanceDetail.getCoachCourseFee().compareTo(BigDecimal.ZERO) > 0){
			coachAmt = coachAmt.add(storeBalanceDetail.getCoachCourseFee());
		}else{
			coachAmt = coachAmt.add(calculationCoachFee(parameMap));
		}
		// 4当期会员续费率(仅月有)
		BigDecimal vipRenewalFeeRate = BigDecimal.valueOf(0);
		if(!StringUtil.isEmpty(yearMonth)){
			vipRenewalFeeRate = vipRenewalFeeRate.add(dataCenterMapper.queryVipOrderRepeatChargeRate(storeId, yearMonth.length() > 0 ? yearMonth+"-01":startDate, yearMonth.length() > 0 ?  DateUtils.andMonth(yearMonth+"-01", 1):endDate));// 暂留
		}
		logger.info("=========================== ajax select queryDataAnalysisLevelFour end ================");
		parameMap.put("teamFullClassRate", teamFullClassRate);
		parameMap.put("averagePayCount", df.format(averagePayCount));
		parameMap.put("vipRenewalFeeRate", vipRenewalFeeRate);
		parameMap.put("coachAmt", df.format(coachAmt));
		return parameMap;
	}
	
	/**
	 * 汇总类数据（2016.12.01至当前的数据汇总）
	 */
	@Override
	public Map<String, Object> querySummaryDataToNow(Map<String, Object> parameMap) {
		logger.info("=========================== ajax select querySummaryDataToNow start ================");
		String startDate = "2016-11-01";
		String endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
		Integer storeId = (Integer) parameMap.get("storeId");
		String yearMonth = "";
		DecimalFormat df=new DecimalFormat(",###,###.###");
		// TODO Auto-generated method stub
		StoreInfo storeInfo = new StoreInfo();
		/*if(storeId > 0){
			storeInfo = storeInfoMapper.selectByPrimaryKey(storeId);
			startDate = DateUtils.format(storeInfo.getCreatedTime(), "yyyy-MM-dd");
		}*/
		// 1 零售订单总笔数
		Integer orderCount = dataCenterMapper.queryRetailOrderCount(storeId, startDate, endDate, yearMonth);
		// 2零售总流水
		BigDecimal orderWater = dataCenterMapper.queryRetailOrderRunningAccountAmt(storeId, startDate, endDate, yearMonth);
		// 3零售总实收
		List<DataCenterOrderIncomeAmtModel> incomeAmtList = dataCenterMapper.queryRetailRealIncomeAmt(storeId, startDate, endDate, yearMonth);
		BigDecimal incomeAmt = BigDecimal.valueOf(0);
		if(incomeAmtList.size() > 0){
			for(DataCenterOrderIncomeAmtModel d:incomeAmtList){
				incomeAmt = incomeAmt.add(d.getIncomeAmt());
			}
		}
		// 4付费总人数
		List<DataCenterOrderDetailModel> orderPayList = dataCenterMapper.queryPayerCountDetail(storeId, startDate, endDate, yearMonth);
		Integer payCount = 0;
		if(orderPayList.size() > 0){
			for(DataCenterOrderDetailModel d:orderPayList){
				payCount = payCount + d.getAllOrderCount();
			}
		}
		
		
		// 1 当前在线会员总数
		Integer vipCount = dataCenterMapper.userIsVipCountToNow(storeId, startDate, endDate);
		vipCount = vipCount > 0 ? vipCount : 0;
		// 2会员总流水
		BigDecimal vipWater = BigDecimal.valueOf(0);
		vipWater = vipWater.add(dataCenterMapper.queryVIPOrderAmt(storeId, startDate, endDate, yearMonth));
		// 3会员总实收
		BigDecimal vipAmt = BigDecimal.valueOf(0);
		vipAmt = vipAmt.add(dataCenterMapper.queryVipRealIncomeAmt(storeId, startDate, endDate));
		// 4会员续费率
		BigDecimal vipRenewalFeeRate = BigDecimal.valueOf(0);
		vipRenewalFeeRate = vipRenewalFeeRate.add(dataCenterMapper.queryVipOrderRepeatChargeRate(storeId, startDate, endDate));
		
		// 1 流失会员总数
		Integer vipLost = dataCenterMapper.queryVipLost(storeId, startDate, endDate, yearMonth);
		vipLost = vipLost > 0 ? vipLost : 0 ;
		// 2会员零售转化率
		BigDecimal vipRetailRate = BigDecimal.valueOf(0);
		vipRetailRate = vipRetailRate.add(dataCenterMapper.queryVipRetailRechargeRate(storeId, startDate, endDate));
		// 3会员自助转化率
		BigDecimal vipSelfRetailRate = BigDecimal.valueOf(0);
		vipSelfRetailRate = vipSelfRetailRate.add(dataCenterMapper.queryVipSelfRechargeRate(storeId, startDate, endDate));
		// 4零售复购率
		BigDecimal retailRate = BigDecimal.valueOf(0);
		retailRate = retailRate.add(dataCenterMapper.queryRetailRepeatChargeRate(startDate,endDate, "3"));
		
		// 1 团课平均满课率
		BigDecimal teamFullClassRate = BigDecimal.valueOf(0);
		teamFullClassRate = teamFullClassRate.add(dataCenterMapper.queryTeamFullClassRate(storeId,startDate,endDate));
		
		// 2用户平均购买次数
		BigDecimal averagePayCount = BigDecimal.valueOf(0);
		averagePayCount = averagePayCount.add(dataCenterMapper.queryAveragePayNumberToUser(storeId, startDate, endDate,yearMonth));
		
		// 包月卡 
		Integer cardBool = dataCenterMapper.queryStoreIsHaveCard(storeId);
		if(cardBool > 0){
			// 统计购买包月卡的会员数
			Integer monthCardNum = dataCenterMapper.queryMonthCardCount(storeId, startDate, endDate, yearMonth);
			// 统计当前包月卡的流水
			BigDecimal monthCardWater = dataCenterMapper.queryMonthCardRunningAccountAmt(storeId, startDate, endDate, yearMonth);
			// 统计当前包月卡的实收
			BigDecimal monthCardAmt = dataCenterMapper.queryMonthCardRealIncomeAmt(storeId, startDate, endDate, yearMonth);
			parameMap.put("monthCardNum", df.format(monthCardNum));
			parameMap.put("monthCardWater", df.format(monthCardWater.setScale(2,BigDecimal.ROUND_UP)));
			parameMap.put("monthCardAmt", df.format(monthCardAmt.setScale(2,BigDecimal.ROUND_UP)));
		}
		parameMap.put("orderCount", df.format(orderCount));
		parameMap.put("orderWater", df.format(orderWater.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("incomeAmt", df.format(incomeAmt.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("payCount", df.format(payCount));
		parameMap.put("vipCount", df.format(vipCount));
		parameMap.put("vipWater", df.format(vipWater.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("vipAmt", df.format(vipAmt.setScale(2,BigDecimal.ROUND_UP)));
		parameMap.put("vipRenewalFeeRate", vipRenewalFeeRate);
		parameMap.put("vipLost", df.format(vipLost));
		parameMap.put("vipRetailRate", vipRetailRate);
		parameMap.put("vipSelfRetailRate", vipSelfRetailRate);
		parameMap.put("retailRate", retailRate);
		parameMap.put("teamFullClassRate", teamFullClassRate);
		parameMap.put("averagePayCount", df.format(averagePayCount));
		logger.info("=========================== ajax select querySummaryDataToNow end ================");
		return parameMap;
	}
	
	/**
	 * 教练复购率排行
	 */
	@Override
	public Map<String, Object> repurchaseRateRankingToCoach(Map<String, Object> parameMap) {
		String dateTime = (String) parameMap.get("dateTime");
		String startDate = null;
		String endDate = null;
		// 没有传值就是默认是今天
		if(StringUtil.isEmpty(dateTime)){
			startDate = DateUtils.format(new Date(), "yyyy-MM-dd");
			endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
		}else{
			startDate = dateTime.split("~")[0];
			endDate = dateTime.split("~")[1];
		}
		List<DataCenterSortResultModel>  coachList= dataCenterMapper.queryCoachSortList(startDate, endDate);
		parameMap.put("coachList", coachList);
		return parameMap;
	}
	
	/**
	 * 课程复购率排行
	 */
	@Override
	public Map<String, Object> repurchaseRateRankingToCourse(Map<String, Object> parameMap) {
		String dateTime = (String) parameMap.get("dateTime");
		String startDate = null;
		String endDate = null;
		// 没有传值就是默认是今天
		if(StringUtil.isEmpty(dateTime)){
			startDate = DateUtils.format(new Date(), "yyyy-MM-dd");
			endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
		}else{
			startDate = dateTime.split("~")[0];
			endDate = dateTime.split("~")[1];
		}
		List<DataCenterSortResultModel> courseList = dataCenterMapper.queryCourseSortList(startDate, endDate);
		parameMap.put("courseList", courseList);
		return parameMap;
	}
	
	/**
	 * 团课满课率排行
	 */
	@Override
	public Map<String, Object> teamFullClassRateRanking(Map<String, Object> parameMap) {
		String dateTime = (String) parameMap.get("dateTime");
		String startDate = null;
		String endDate = null;
		// 没有传值就是默认是今天
		if(StringUtil.isEmpty(dateTime)){
			startDate = DateUtils.format(new Date(), "yyyy-MM-dd");
			endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
		}else{
			startDate = dateTime.split("~")[0];
			endDate = dateTime.split("~")[1];
		}
		List<DataCenterSortResultModel> teamFullList = dataCenterMapper.queryTeamFullClassRateSort(startDate, endDate);
		parameMap.put("teamFullList", teamFullList);
		return parameMap;
	}
	
	/**
	 * 大盘数据查看数据明细
	 */
	@Override
	public Map<String, Object> dataAnalysisDetail(Map<String, Object> parameMap) {
		Integer storeId = (Integer) parameMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = "";
		String type = (String) parameMap.get("type");
		String query_type = (String) parameMap.get("query_type");
		String mode_type = (String) parameMap.get("mode_type");
		try {
			String dateTime = (String)parameMap.get("dateTime");
			if("1".equals(mode_type)){
				startDate = "2016-11-01";
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
			}else{
				if(StringUtil.isEmpty(dateTime)){
					startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
					endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
					parameMap.put("dateTime", startDate);
				}else{
					if("1".equals(type)){
						startDate = dateTime.split("~")[0];
						endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
					}else if("2".equals(type)){
						startDate = dateTime.split("~")[0];
						endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
					}else{
						yearMonth = dateTime ;
					}
				}
			}
			
			List<DataCenterOrderDetailModel> list = null;
			List<DataCenterOrderIncomeAmtModel> listAmt = null;
			List<DataCenterVIPDeatilModel> listVip = null;
			// 开始查询数据
			switch (query_type) {
			// 1 当期零售订单笔数详情
			case "orderCount":
				list = dataCenterMapper.queryRetailOrderCountDetail(storeId, startDate, endDate, yearMonth);
				parameMap.put("list", list);
				break;
			// 2当期零售流水详情	
			case "orderWater":
				listAmt = dataCenterMapper.queryRetailOrderRunningAccountAmtDetail(storeId, startDate, endDate, yearMonth);	
				parameMap.put("list", listAmt);
				break;
			// 3当期零售实收金额详情	
			case "orderRevenueAmt":
				listAmt = dataCenterMapper.queryRetailRealIncomeAmt(storeId, startDate, endDate, yearMonth);	
				parameMap.put("list", listAmt);
				break;
			// 4当期付费总人数	
			case "orderPayNumber":
				list = dataCenterMapper.queryPayerCountDetail(storeId, startDate, endDate, yearMonth);	
				parameMap.put("list", list);
				break;
			// 1当期新增会员 	
			case "vipNum":
				listVip = dataCenterMapper.queryNweVipCountDetail(storeId, startDate, endDate, yearMonth);
				parameMap.put("list", listVip);
				break;
			// 2当期新增会员流水
			case "vipWater":
				listVip = dataCenterMapper.queryVIPOrderAmtDetail(storeId, startDate, endDate, yearMonth);
				parameMap.put("list", listVip);
				break;	
			// 3当期会员实收
			case "vipAmt":
				//parameMap.put("list", dataCenterMapper.queryVIPOrderAmtDetail(storeId, startDate, endDate, yearMonth));
				break;
			// 4当期流失会员数
			case "vipLost":
				List<DataCenterUserStort> listUserS = dataCenterMapper.queryVipLostDetail(storeId, startDate, endDate, yearMonth.length() > 0 ? yearMonth+"-01":yearMonth);
				parameMap.put("list", listUserS);
				break;
			// 1当期会员零售转化率
			case "vipConversionRate":
				// 
				break;
			// 3当期零售复购率	
			case "retailRechargeRate":
				BigDecimal userRate = dataCenterMapper.queryRetailRepeatChargeRate(startDate, endDate, "1");
				BigDecimal vipRate = dataCenterMapper.queryRetailRepeatChargeRate(startDate, endDate, "2");
				BigDecimal allRate = dataCenterMapper.queryRetailRepeatChargeRate(startDate, endDate, "3");
				List<String> listRate = new ArrayList<>();
				listRate.add("总部："+allRate);
				listRate.add("会员："+vipRate);
				listRate.add("非会员："+userRate);
				parameMap.put("list", listRate);
				break;
			// 当前在线用户数量
			case "vipCount":
				List<DataCenterUserStort> userStortList = dataCenterMapper.queryUserStortByLevel("2");
				parameMap.put("list", userStortList);
				break;
			default:
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return parameMap;
	}

	/**
	 * 门店经营分析数据
	 */
	@Override
	public Map<String, Object> storeFinancialAnalysisData(Map<String, Object> paramMap) {
		Map<String,Object> respMap = new HashMap<String,Object>();
		// TODO Auto-generated method stub
		Integer storeId = (Integer)paramMap.get("storeId");
		String yearMonth = (String)paramMap.get("yearMonth");
		String startDate = yearMonth+"-01";
		String endDate = DateUtils.andMonth(startDate, 1);
			
		//门店会员流水
		BigDecimal storeVipOrderAmt =  new BigDecimal(0);
		storeVipOrderAmt =  dataCenterMapper.queryVIPOrderAmt(storeId, null, null, yearMonth);
		respMap.put("storeVipOrderAmt", storeVipOrderAmt);
		//门店零售流水
		BigDecimal storeRetailOrderAmt = new BigDecimal(0);
		storeRetailOrderAmt = dataCenterMapper.queryRetailOrderRunningAccountAmt(storeId, null, null, yearMonth);
		respMap.put("storeRetailOrderAmt", storeRetailOrderAmt);
		
		//门店零售实收
	    List<DataCenterOrderIncomeAmtModel> retailRealIncomeList =dataCenterMapper.queryRetailRealIncomeAmt(storeId, null, null, yearMonth);
	    BigDecimal storeRetailRealIncomeAmt = new BigDecimal(0);
	    if(retailRealIncomeList!=null&&retailRealIncomeList.size()>0){
	    	storeRetailRealIncomeAmt = retailRealIncomeList.get(0).getIncomeAmt();
	    }
	    
	    respMap.put("storeRetailRealIncomeAmt", storeRetailRealIncomeAmt);
		
	    //门店会员实收
	    BigDecimal storeVipRealIncomeAmt  = new BigDecimal(0);  
	      storeVipRealIncomeAmt=	dataCenterMapper.queryVipRealIncomeAmt(storeId, startDate, endDate);
	    
	    respMap.put("storeVipRealIncomeAmt", storeVipRealIncomeAmt);
		//团课包月卡订单流水
		BigDecimal monthTeamCardOrderAmt = new BigDecimal(0);
			monthTeamCardOrderAmt =	dataCenterMapper.queryMonthCardRunningAccountAmt(storeId, startDate, endDate, yearMonth);
		// 统计当前包月卡的实收
		BigDecimal monthTeamCardRealIncomeAmt = new BigDecimal(0);
			monthTeamCardRealIncomeAmt =	dataCenterMapper.queryMonthCardRealIncomeAmt(storeId, startDate,endDate,yearMonth);
		respMap.put("monthTeamCardOrderAmt",monthTeamCardOrderAmt);
		respMap.put("monthTeamCardRealIncomeAmt",monthTeamCardRealIncomeAmt);

	    
	    BigDecimal storeCoachAmt = new BigDecimal(0);
	    storeCoachAmt = calculationCoachFee(paramMap);
	    respMap.put("storeCoachAmt", storeCoachAmt);
	 
	    
	    //企业收入流水
	    BigDecimal storeCompanyFlowFee = new BigDecimal(0);
	    //企业实际收入
	    BigDecimal storeCompanyRealFee = new BigDecimal(0);
	    //门店其他支出
	    BigDecimal storeOtherFee = new BigDecimal(0);
	    //门店实际租金
	    BigDecimal storeRealRentFee = new BigDecimal(0);
	    

	    
	    StoreBalanceDetail storeBalanceDetail = storeBalanceDetailMapper.queryStoreBalanceDetailBy(paramMap);
	    if(storeBalanceDetail !=null){
	    	if(storeBalanceDetail.getCompanyFlowFee()!=null){
	    		storeCompanyFlowFee=storeBalanceDetail.getCompanyFlowFee();
	    	}
	    	if(storeBalanceDetail.getCompanyRealFee()!=null){
	    		storeCompanyRealFee=storeBalanceDetail.getCompanyRealFee();
	    	}
	    	if(storeBalanceDetail.getStoreOtherFee()!=null){
	    		storeOtherFee = storeBalanceDetail.getStoreOtherFee();
	    	}
	    	if(storeBalanceDetail.getStoreRentFee()!=null){
	    		storeRealRentFee=storeBalanceDetail.getStoreRentFee();
	    	}
	    	if(storeBalanceDetail.getCoachCourseFee() != null && storeBalanceDetail.getCoachCourseFee().compareTo(BigDecimal.ZERO) > 0){
	    		storeCoachAmt = storeBalanceDetail.getCoachCourseFee() ;
	    		
	    	}
	    }
	    if(storeRealRentFee.compareTo(new BigDecimal(0))<1){
		    StoreInfo storeInfo = storeInfoMapper.selectById(storeId);
		    if(storeInfo!=null && storeInfo.getStoreRent()!=null){
		    	storeRealRentFee = storeInfo.getStoreRent();	
		    }
	    }
	    respMap.put("storeCoachAmt",storeCoachAmt );
	    respMap.put("storeCompanyFlowFee", storeCompanyFlowFee);
	    respMap.put("storeCompanyRealFee", storeCompanyRealFee);
	    respMap.put("storeOtherFee", storeOtherFee);
	    respMap.put("storeRealRentFee", storeRealRentFee);
	    return respMap;
	}

	/**
	 * 计算教练收入
	 * storeId：按门店
	 * yearMonth:按月计算
	 * startDate：开始日期
	 * endDate：结束日期
	 * @param paramMap
	 * @return
	 */
	public BigDecimal calculationCoachFee(Map<String, Object> paramMap) {
		
		BigDecimal storeCampCoachAmt = new BigDecimal(0);
	    //门店檬营教练费用
	    List<CampCountFeeDetail> campList =  coachSigninLogMapper.queryCampCoachFee(paramMap);
	    if(campList!=null){
	    	for(CampCountFeeDetail campCountFeeDetail :campList){
	    		storeCampCoachAmt = storeCampCoachAmt.add(campCountFeeDetail.getPlanA().compareTo(campCountFeeDetail.getPalnB())>0?campCountFeeDetail.getPlanA():campCountFeeDetail.getPalnB());
	    	}
	    }
	    
	  
	    //门店私教教练费用
	    List<CoursePrivteFeeVO> storePtCoachAmtList =   courseSignMapper.queryPrivateCoachFee(paramMap);
	    BigDecimal storePtCoachAmt = new BigDecimal(0);
	    if(storePtCoachAmtList !=null){
	    	for(CoursePrivteFeeVO vo:storePtCoachAmtList){
		    	storePtCoachAmt = storePtCoachAmt.add(vo.getReal_amt());
		    }	
	    }
	    //门店团课教练费用
	    
	    List<CoachFeeDetailVo> coachFeeDetailVoList =  courseInfoMapper.queryCoachFeeDetail(paramMap);
	    BigDecimal storeTeamCoachAmt = new BigDecimal(0);
	    if(coachFeeDetailVoList !=null){
	    	for(CoachFeeDetailVo dvo : coachFeeDetailVoList){
	    		storeTeamCoachAmt = storeTeamCoachAmt.add(dvo.getBlankCourse()).add(dvo.getHotCourse()).add(dvo.getNomalCourse());
	    	}
	    }
	    //门店教练费用
	    BigDecimal storeCoachAmt = storeCampCoachAmt.add(storePtCoachAmt).add(storeTeamCoachAmt);
	   
	    return storeCoachAmt;
	}	
	
	/**
	 * 收支曲线图
	 */
	public Map<String,Object> queryBalanceMapByYearMonthRange(Map<String,Object> paramMap){
		Map<String,Object> respMap = new HashMap<String,Object>();
		Integer storeId = (Integer) paramMap.get("storeId");
		List<String> yearMonthList =(List)paramMap.get("yearMonthList");
		List columns = new ArrayList();
		List x = new ArrayList();
		x.add("x");
		List allFlowFeeList = new ArrayList();
		allFlowFeeList.add("流水");
		List allRealFeeList = new ArrayList();
		allRealFeeList.add("实收");
		List allPayFeeList = new ArrayList();
		allPayFeeList.add("支出");
		for(String yearMonth:yearMonthList){
		   Map<String,Object> param = new HashMap<String,Object>();
		   param.put("storeId", storeId);
		   param.put("yearMonth", yearMonth);
		   x.add(yearMonth);
		   Map<String,Object> result = storeFinancialAnalysisData(param);
		   BigDecimal allFlowFee = new BigDecimal(0);
		   BigDecimal allRealFee = new BigDecimal(0);
		   BigDecimal allPayFee = new BigDecimal(0);
		   allFlowFee =((BigDecimal)result.get("storeVipOrderAmt")).add((BigDecimal)result.get("storeRetailOrderAmt")).add((BigDecimal)result.get("storeCompanyFlowFee"));
		   allRealFee =((BigDecimal)result.get("storeVipRealIncomeAmt")).add((BigDecimal)result.get("storeRetailRealIncomeAmt")).add((BigDecimal)result.get("storeCompanyRealFee"));
		   allPayFee =((BigDecimal)result.get("storeCoachAmt")).add((BigDecimal)result.get("storeRealRentFee")).add((BigDecimal)result.get("storeOtherFee"));
		   allFlowFeeList.add(allFlowFee);
		   allRealFeeList.add(allRealFee);
		   allPayFeeList.add(allPayFee);
		}
		columns.add(x);
		columns.add(allFlowFeeList);
		columns.add(allRealFeeList);
		columns.add(allPayFeeList);
		respMap.put("columns", columns);
		return respMap;
	}

	@Override
	public void saveOrUpdateStoreBalanceDetail(Map<String, Object> paramMap) {
		Map<String,Object> respMap = new HashMap<String,Object>();
		Integer storeId =(Integer) paramMap.get("storeId");
		String yearMonth = (String) paramMap.get("yearMonth");
		String updateAmt = (String) paramMap.get("updateAmt");
		String type = (String) paramMap.get("type");
		StoreBalanceDetail entity = new StoreBalanceDetail();
		BigDecimal amt = new BigDecimal(updateAmt);
		entity.setStoreId(storeId);
		entity.setYearMonth(yearMonth);
		StoreBalanceDetail resultDetail =storeBalanceDetailMapper.selectOne(entity);
		if(resultDetail!=null){
			if("1".equals(type)){
				resultDetail.setCompanyFlowFee(amt);
			}else if("2".equals(type)){
				resultDetail.setCompanyRealFee(amt);
			}else if("3".equals(type)){
				resultDetail.setStoreOtherFee(amt);
			}else if("4".equals(type)) {
				resultDetail.setStoreRentFee(amt);
			}else if("5".equals(type)) {
				resultDetail.setCoachCourseFee(amt);
			}
			
			resultDetail.setUpdateTime(new Date());
			storeBalanceDetailMapper.updateById(resultDetail);
		}else{
			if("1".equals(type)){
				entity.setCompanyFlowFee(amt);
			}else if("2".equals(type)){
				entity.setCompanyRealFee(amt);
			}else if("3".equals(type)){
				entity.setStoreOtherFee(amt);
			}else if("4".equals(type)) {
				entity.setStoreRentFee(amt);
			}else if("5".equals(type)) {
				entity.setCoachCourseFee(amt);
			}
			entity.setCreatedTime(new Date());
			storeBalanceDetailMapper.insert(entity);
		}
	}
	
	/**
	 * 统计门店包月卡相关数据
	 * 这里的统计还是针对单门店来统计还没有涉及到多门店的统计
	 * 和门店交叉的统计
	 */
	@Override
	public Map<String, Object> queryMonthCard(Map<String, Object> paramMap) {
		logger.info("=========================== ajax select queryMonthCard start ================");
		
		Integer storeId = (Integer) paramMap.get("storeId");
		String startDate = null;
		String endDate = null;
		String yearMonth = "";
		String type = (String) paramMap.get("type");
		DecimalFormat df=new DecimalFormat(",###,###.##");
		try {
			String dateTime = (String)paramMap.get("dateTime");
			if(StringUtil.isEmpty(dateTime)){
				startDate = DateUtils.format(new Date(),"yyyy-MM-dd");
				endDate = DateUtils.format(DateUtils.addMinutes(new Date(), 60*24), "yyyy-MM-dd");
				paramMap.put("dateTime", startDate);
			}else{
				if("1".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else if("2".equals(type)){
					startDate = dateTime.split("~")[0];
					endDate = DateUtils.format(DateUtils.addMinutes(DateUtils.toDate(dateTime.split("~")[1]), 60*24), "yyyy-MM-dd");
				}else{
					yearMonth = dateTime ;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		// 统计购买包月卡的会员数
		Integer monthCardNum = dataCenterMapper.queryMonthCardCount(storeId, startDate, endDate, yearMonth);
		// 统计当前包月卡的流水
		BigDecimal monthCardWater = dataCenterMapper.queryMonthCardRunningAccountAmt(storeId, startDate, endDate, yearMonth);
		// 统计当前包月卡的实收 
		BigDecimal monthCardAmt = dataCenterMapper.queryMonthCardRealIncomeAmt(storeId, StringUtil.isEmpty(yearMonth) == false ? yearMonth+"-01":startDate, StringUtil.isEmpty(yearMonth) == false ? DateUtils.andMonth(yearMonth+"-01", 1):endDate, yearMonth);
		paramMap.put("monthCardNum", df.format(monthCardNum));
		paramMap.put("monthCardWater", df.format(monthCardWater.setScale(2,BigDecimal.ROUND_UP)));
		paramMap.put("monthCardAmt", df.format(monthCardAmt.setScale(2,BigDecimal.ROUND_UP)));
		logger.info("=========================== ajax select queryMonthCard end ================");
		return paramMap;
	}

}
